package yunjiao.javatutorials.lang.concurrent.interrupt;

/**
 * 基础中断检查示例
 *
 * @author yangyunjiao
 */
public class BasicInterruptExample {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(new RunnableTask());
        worker.start();

        // 主线程休眠2秒后中断工作线程
        Thread.sleep(2000);
        worker.interrupt();
        System.out.println("主线程发送中断信号");
    }

    static class RunnableTask implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("工作线程正在运行...");
                try {
                    Thread.sleep(500); // 模拟工作
                } catch (InterruptedException e) {
                    System.out.println("线程在休眠时被中断，中断状态: " +
                            Thread.currentThread().isInterrupted());
                    // 收到中断异常后，中断状态会被清除，需要重新设置
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println("工作线程结束，中断状态: " +
                    Thread.currentThread().isInterrupted());
        }
    }
}
